package com.sxf.rental.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sxf.rental.entity.User;
import com.sxf.rental.entity.UserRole;
import com.sxf.rental.mapper.UserMapper;
import com.sxf.rental.mapper.UserRoleMapper;
import com.sxf.rental.service.IOssService;
import com.sxf.rental.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author sxf
 * @since 2025-03-08
 */
@Service
@Transactional
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    private IOssService ossService;

    @Resource
    private UserRoleMapper userRoleMapper;



    @Override
    public User selectByUsername(String username) {
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("username",username);
        return baseMapper.selectOne(queryWrapper);
    }

    @Override
    public List<String> selectRoleName(int id) {
        return baseMapper.selectRoleNameByUserId(id);
    }

    @Override
    public Page<User> searchByPage(Page<User> page, User user) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (user.getDeptId()!=null && user.getDeptId() ==0){
            queryWrapper.like(StrUtil.isNotEmpty(user.getUsername()), "username", user.getUsername());
            queryWrapper.like(StrUtil.isNotEmpty(user.getRealname()), "realname", user.getRealname());
            queryWrapper.like(StrUtil.isNotEmpty(user.getNickname()), "nickname", user.getNickname());
            queryWrapper.like(StrUtil.isNotEmpty(user.getPhone()), "phone", user.getPhone());
            queryWrapper.like(StrUtil.isNotEmpty(user.getEmail()), "email", user.getEmail());
            return baseMapper.selectPage(page,queryWrapper);
        }
        queryWrapper.eq(ObjectUtil.isNotEmpty(user.getDeptId()), "dept_id", user.getDeptId());
        queryWrapper.like(StrUtil.isNotEmpty(user.getUsername()), "username", user.getUsername());
        queryWrapper.like(StrUtil.isNotEmpty(user.getRealname()), "realname", user.getRealname());
        queryWrapper.like(StrUtil.isNotEmpty(user.getNickname()), "nickname", user.getNickname());
        queryWrapper.like(StrUtil.isNotEmpty(user.getPhone()), "phone", user.getPhone());
        queryWrapper.like(StrUtil.isNotEmpty(user.getEmail()), "email", user.getEmail());
        return baseMapper.selectPage(page, queryWrapper);
    }


    public boolean delete(String ids) {
        List<Integer> list = Arrays.stream(ids.split(",")).map(Integer::parseInt).toList();
        try{
            if (!list.isEmpty()){
                    list.forEach(id -> {
                        User user=baseMapper.selectById(id);
                        if (user.getIsAdmin()!=null && user.getIsAdmin() != 1){
                            //删除用户头像
                            if (user.getAvatar()!=null){
                                ossService.delete(user.getAvatar());
                            }
                            //删除用户
                            baseMapper.deleteById(id);
                            //删除用户和角色的关联数据
                            userRoleMapper.delete(new QueryWrapper<UserRole>().eq("user_id", id));

                        }
                    });
            }
            return true;
        }catch (Exception e) {
            throw new RuntimeException("删除失败");
        }
    }

    @Override
    public boolean bindRole(Integer userId, List<Integer> list) {
        //先删除当前用户所关联所有角色
        userRoleMapper.delete(new QueryWrapper<UserRole>().eq("user_id", userId));
        //重新插入用户和角色关联
        if (!list.isEmpty()){
            list.forEach(roleId -> {
                UserRole userRole=new UserRole();
                userRole.setRoleId(roleId);
                userRole.setUserId(userId);
                userRoleMapper.insert(userRole);
            });
        }
            return true;
    }


}
